package com.eden.door.util;

import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

import com.eden.door.constant.Constant_Sys;
import com.eden.door.entity.Door;
import com.eden.door.entity.DoorAttr;
import com.eden.door.entity.Formula;
import com.eden.door.entity.Option;

public class DoorUtil {
	
	public static Door calculate(Door door) {
		List<? extends Formula> formulaList = door.getFormulaList() ;
		
		Map<String, DoorAttr> doorAttrMap = door.getDoorAttrs() ;
		//计算门的属性
		for(Formula formula : formulaList){
			doorAttrMap = formula.calculate(doorAttrMap) ;
		}
		door.setDoorAttrs(doorAttrMap) ;
		
		return door ;
	}
	
	
	/**
	 * 从门属性集中取的显示的文本内容
	 * @param name
	 * @param doorAttrMap
	 * @return
	 */
	public static String getTextByName(String name , Map<String , DoorAttr> doorAttrMap){
		String text = "" ;
		
		Entry<String , DoorAttr> entry ;
		DoorAttr doorAttr ;
		
		//数值显示格式化,显示小数点后两位
		DecimalFormat format = new DecimalFormat(".##") ;
		
		for(Iterator<Entry<String, DoorAttr>> i = doorAttrMap.entrySet().iterator() ; i.hasNext();){
			entry = i.next();
			doorAttr = entry.getValue() ;
			
			if(StringUtils.equals(name, doorAttr.getName())){
				text = doorAttr.getValue() ;
				//格式化输出
				if(StringUtils.equals(doorAttr.getFill(), Constant_Sys.DOOR_ATTR_FILL_AUTO)){
					return format.format(Double.valueOf(text)) ;
				}
				/*if(StringUtils.equals(Constant_Sys.DOOR_ATTR_TYPE_TEXT, doorAttr.getType())){
					text = doorAttr.getValue() ;
				} else if(StringUtils.equals(Constant_Sys.DOOR_ATTR_TYPE_SELECT, doorAttr.getType())){
					List<Option> optList = doorAttr.getOptList() ;
					for(Option p : optList){
						if(StringUtils.equals(p.getValue(), doorAttr.getValue())){
							text = p.getText() ;
							break ;
						}
					}
				}*/
			}
		}
		
		return text ;
	}
	
	@SuppressWarnings("unchecked")
	public static String showDoorAttrValue(Object c){
		StringBuilder sb = new StringBuilder() ;
		if(c instanceof Map){
			for(Iterator<Entry<String,DoorAttr>> i = ((Map<String,DoorAttr>) c).entrySet().iterator() ; i.hasNext();){
				DoorAttr doorAttr = i.next().getValue() ; 
				sb.append(doorAttr.getName() + " : " + doorAttr.getValue() + " ; ") ;
			}
		} else if(c instanceof List){
			for(DoorAttr doorAttr : ((List<DoorAttr>)c)){
				sb.append(doorAttr.getName() + " : " + doorAttr.getValue() + " ; ") ;
			}
		}
		
		
		return sb.toString() ;
	}
}
